package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.dto.content.ContentAddRequest;
import com.yupi.yuoj.model.dto.content.ContentEditRequest;
import com.yupi.yuoj.model.dto.content.ContentQueryRequest;
import com.yupi.yuoj.model.dto.content.ContentUpdateRequest;
import com.yupi.yuoj.model.entity.Content;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.vo.ContentVO;
import com.yupi.yuoj.service.ContentService;
import com.yupi.yuoj.service.UserService;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 内容接口
 *
 * @author jingjin
 */
@RestController
@RequestMapping("/content")
@Slf4j
public class ContentController {

    @Resource
    private ContentService contentService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param contentAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addContent(@RequestBody ContentAddRequest contentAddRequest, HttpServletRequest request) {
        if (contentAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Content content = new Content();
        BeanUtils.copyProperties(contentAddRequest, content);
        List<String> tags = contentAddRequest.getTags();
        if (tags != null) {
            content.setTags(GSON.toJson(tags));
        }
        contentService.validContent(content, true);
        User loginUser = userService.getLoginUser(request);
        content.setUserId(loginUser.getId());
        content.setLikeNum(0);
        content.setCollectionNum(0);
        content.setViewNum(0);
        content.setCommentNum(0);
        content.setStatus(0); // 默认草稿状态
        boolean result = contentService.save(content);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newContentId = content.getId();
        return ResultUtils.success(newContentId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteContent(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Content oldContent = contentService.getById(id);
        ThrowUtils.throwIf(oldContent == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅管理员可删除 (Content表暂无user_id字段，无法验证所有者)
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = contentService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param contentUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateContent(@RequestBody ContentUpdateRequest contentUpdateRequest) {
        if (contentUpdateRequest == null || contentUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Content content = new Content();
        BeanUtils.copyProperties(contentUpdateRequest, content);
        List<String> tags = contentUpdateRequest.getTags();
        if (tags != null) {
            content.setTags(GSON.toJson(tags));
        }
        // 参数校验
        contentService.validContent(content, false);
        long id = contentUpdateRequest.getId();
        // 判断是否存在
        Content oldContent = contentService.getById(id);
        ThrowUtils.throwIf(oldContent == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = contentService.updateById(content);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ContentVO> getContentVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Content content = contentService.getById(id);
        if (content == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(contentService.getContentVO(content, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param contentQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ContentVO>> listContentVOByPage(@RequestBody ContentQueryRequest contentQueryRequest,
            HttpServletRequest request) {
        long current = contentQueryRequest.getCurrent();
        long size = contentQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Content> contentPage = contentService.page(new Page<>(current, size),
                contentService.getQueryWrapper(contentQueryRequest));
        return ResultUtils.success(contentService.getContentVOPage(contentPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param contentQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ContentVO>> listMyContentVOByPage(@RequestBody ContentQueryRequest contentQueryRequest,
            HttpServletRequest request) {
        if (contentQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        contentQueryRequest.setUserId(loginUser.getId());
        long current = contentQueryRequest.getCurrent();
        long size = contentQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Content> contentPage = contentService.page(new Page<>(current, size),
                contentService.getQueryWrapper(contentQueryRequest));
        return ResultUtils.success(contentService.getContentVOPage(contentPage, request));
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param contentEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editContent(@RequestBody ContentEditRequest contentEditRequest, HttpServletRequest request) {
        if (contentEditRequest == null || contentEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Content content = new Content();
        BeanUtils.copyProperties(contentEditRequest, content);
        List<String> tags = contentEditRequest.getTags();
        if (tags != null) {
            content.setTags(GSON.toJson(tags));
        }
        // 参数校验
        contentService.validContent(content, false);
        User loginUser = userService.getLoginUser(request);
        long id = contentEditRequest.getId();
        // 判断是否存在
        Content oldContent = contentService.getById(id);
        ThrowUtils.throwIf(oldContent == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅管理员可编辑 (Content表暂无user_id字段，无法验证所有者)
        if (!userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = contentService.updateById(content);
        return ResultUtils.success(result);
    }

    /**
     * 发布内容
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/publish")
    public BaseResponse<Boolean> publishContent(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Content oldContent = contentService.getById(id);
        ThrowUtils.throwIf(oldContent == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅管理员可发布 (Content表暂无user_id字段，无法验证所有者)
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        Content content = new Content();
        content.setId(id);
        content.setStatus(1); // 设置为已发布
        boolean result = contentService.updateById(content);
        return ResultUtils.success(result);
    }

}